/**
 * @Title: WorkVisitActivity.java
 * @Package: com.jason.fingerprint.ui
 * @Descripton: TODO
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年11月9日 下午8:00:43
 * @Version: V1.0
 */
package com.jason.fingerprint.ui;

import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.kymjs.aframe.database.DbModel;
import org.kymjs.aframe.database.KJDB;
import org.kymjs.aframe.ui.BindView;
import org.kymjs.aframe.ui.KJActivityManager;
import org.kymjs.aframe.ui.activity.BaseActivity;
import org.kymjs.aframe.utils.StringUtils;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.fpi.MtRfid;
import android.media.AudioManager;
import android.media.MediaRecorder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android_serialport_api.FingerprintManager;

import com.baidu.location.LocationClient;
import com.jason.fingerprint.AppContext;
import com.jason.fingerprint.R;
import com.jason.fingerprint.adapter.WorkVisitAdapter;
import com.jason.fingerprint.beans.RecordBean;
import com.jason.fingerprint.beans.WorkVisitBean;
import com.jason.fingerprint.beans.ui.FingerPrintBean;
import com.jason.fingerprint.beans.ui.ImageOrAudioBean;
import com.jason.fingerprint.beans.ui.LocationBean;
import com.jason.fingerprint.common.DataHelper;
import com.jason.fingerprint.common.DialogHelper;
import com.jason.fingerprint.common.RemainingTimeCalculator;
import com.jason.fingerprint.common.SoundRecorder;
import com.jason.fingerprint.common.SoundRecorder.OnStateChangedListener;
import com.jason.fingerprint.common.UIHelper;
import com.jason.fingerprint.configs.DataConfig;
import com.jason.fingerprint.listener.MyLocationListener;
import com.jason.fingerprint.logic.InsertVisitSyncLogic;
import com.jason.fingerprint.logic.MatchFingerprintSyncLogic;
import com.jason.fingerprint.logic.UploadToTempSyncLogic;
import com.jason.fingerprint.service.SoundRecorderService;
import com.jason.fingerprint.service.SoundRecorderService.SoundRecorderBinder;
import com.jason.fingerprint.widget.LoadingDialog;

/**
 * @ClassName: WorkVisitActivity
 * @Description: 工作走访
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年11月9日 下午8:00:43
 */
@SuppressLint("HandlerLeak")
public class WorkVisitActivity extends BaseActivity implements
		OnItemClickListener, OnStateChangedListener {

	private static final String TAG = "WorkVisitActivity";
	public static final int CHOOSE_PHOTO_REQUEST_OK = 1001;
	public static final int CHOOSE_RECORD_REQUEST_OK = 1002;

	private static final boolean DEBUG = false;

	@BindView(id = R.id.header_back, click = true)
	private Button mBackButton;
	@BindView(id = R.id.header_title)
	private TextView mTitleTextView;
	@BindView(id = R.id.work_visit_listview)
	private ListView mListView;
	@BindView(id = R.id.work_visit_button_sign_in, click = true)
	private Button mSignInButton;
	@BindView(id = R.id.work_visit_button_upload, click = true)
	private Button mUploadButton;

	private LocationBroadcastReceiver mLocationBroadcastReceiver;
	private LocationBean mLocationBean;

	private LocationClient mLocationClient;
	private AppContext mAppContext;
	private Context mContext;
	private WorkVisitAdapter mWorkVisitAdapter;
	private KJDB mKjdb;
	private List<WorkVisitBean> mWorkVisitBeans;
	private int mMaxId;

	private MatchFingerprintSyncLogic mLogic;
	private List<String> mCacheCheckImages = new ArrayList<String>();
	private int mChooseImageCount = 5;

	private RecordBean mRecordBean;
	private LoadingDialog mProgressDialog;
	private SoundRecorderService mService = null;
	private SoundRecorder mRecorder;
	private RemainingTimeCalculator mRemainingTimeCalculator;

	int mAudioSourceType = MediaRecorder.AudioSource.MIC;
	String mRequestedType = DataConfig.AUDIO_AMR;

	private AudioManager mAudioManager;
	private String mLastFileName;

	private ServiceConnection mServiceConnection = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			Log.i(TAG, "<onServiceConnected> Service connected");
			mService = ((SoundRecorderBinder) service).getService();
			mRecorder = mService.getRecorder();
			mRecorder.setOnStateChangedListener(WorkVisitActivity.this);
			mRemainingTimeCalculator = mService.getRemainingTimeCalculator();
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			Log.i(TAG, "<onServiceDisconnected> Service dis connected");
			mService = null;
		}
	};

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.kymjs.aframe.ui.activity.I_KJActivity#setRootView()
	 */
	@Override
	public void setRootView() {
		setContentView(R.layout.activity_work_visit);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.kymjs.aframe.ui.activity.KJFrameActivity#initWidget()
	 */
	@Override
	protected void initWidget() {
		// TODO Auto-generated method stub
		super.initWidget();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.kymjs.aframe.ui.activity.KJFrameActivity#initData()
	 */
	@Override
	protected void initData() {
		super.initData();
		mAppContext = (AppContext) getApplication();
		mContext = getApplicationContext();
		mKjdb = mAppContext.getKjdb();
		mTitleTextView.setText("工作走访");
		mWorkVisitAdapter = new WorkVisitAdapter(mContext);
		try {
			mWorkVisitBeans = mKjdb.findAll(WorkVisitBean.class);
		} catch (Exception e) {
		}
		mWorkVisitAdapter.addAll(mWorkVisitBeans);
		mListView.setAdapter(mWorkVisitAdapter);
		mListView.setOnItemClickListener(this);
		mProgressDialog = new LoadingDialog(this);
        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        bindService(new Intent(this, SoundRecorderService.class),
				this.mServiceConnection, BIND_AUTO_CREATE);
        initFinger();
	}
	
	// 初始化指纹信息
	private void initFinger() {
		mLogic = MatchFingerprintSyncLogic.getInstance();
		mLogic.setFingerPrintReader(FingerprintManager.getInstance()
				.getNewAsyncFingerprint());
		mLogic.setHandle(mFingerpringHandler);
		mLogic.isManager(true);
	}

	private void showPopWindow() {
		mProgressDialog.setMessage("请按指纹...");
		mProgressDialog.show();
		fingerPrintMatch();
	}

	@Override
	protected void onResume() {
		super.onResume();
		Log.i(TAG, "<onResume> start service");
//		if (startService(new Intent(this, SoundRecorderService.class)) == null) {
//			Log.e(TAG, "<onResume> fail to start service");
//			finish();
//			return;
//		}
	}

	@Override
	protected void onDestroy() {
		if (mRecorder != null) {
			mRecorder.removeOnStateChangedListener(this);
		}
		unbindService(mServiceConnection);
		if (mService.getRecordState() == SoundRecorder.STATE_IDLE) {
			stopService(new Intent(this, SoundRecorderService.class));
		}
		super.onDestroy();
	}

	// 开启指纹登录
	private synchronized void fingerPrintMatch() {
		if (DEBUG) {
			// 调试--模拟工作人员指纹
			List<FingerPrintBean> list = mKjdb.findAllByWhere(
					FingerPrintBean.class, "type=2");
			if (list == null || list.isEmpty()) {
				mFingerPrintBean = new FingerPrintBean();
				mFingerPrintBean.setUserName("gpnc");
				mFingerPrintBean.setUserId("100006");
				mFingerPrintBean.setType(2);
			} else {
				Random radom = new Random();
				int i = radom.nextInt(list.size());
				mFingerPrintBean = list.get(i);
			}
			// 选择矫正人员
			if (mFingerPrintBean != null && mFingerPrintBean.getType() == 2) {
				chooseRecordInfo();
			}else {
				Toast.makeText(mContext, "匹配失败", Toast.LENGTH_SHORT).show();
			}		
		} else {
		    mLogic.execute();
		}
	}

	private Handler mFingerpringHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			Message message = new Message();
			switch (msg.what) {
			case UIHelper.FINGERPRINT_UPCHAR_SUCCESS:
				break;
			case UIHelper.FINGERPRINT_UPCHAR_FAIL:// char--返回失败
			case UIHelper.FINGERPRINT_REGMODE_FAIL:// char--模板合成失败
			case UIHelper.FINGERPRINT_GENCHAR_FAIL:// char--生成特征值失败
			case UIHelper.FINGERPRINT_DELETECHAR_FAIL:// char--模板下载失败
			case UIHelper.FINGERPRINT_UPIMAGE_FAIL:// image--生成失败
			case UIHelper.FINGERPRINT_SEARCH_FAIL:
				message.what = 101;
				mMatchHandler.handleMessage(message);
				break;
			case UIHelper.FINGERPRINT_SEARCH_SUCCESS:
				// 匹配成功
				Toast.makeText(mContext, "匹配成功", Toast.LENGTH_SHORT).show();
				int pageId = msg.arg1;
				message.what = 100;
				message.arg1 = pageId;
				mMatchHandler.handleMessage(message);
				break;
			case UIHelper.FINGERPRINT_AGAIN:// 再次按手指
				mProgressDialog.setMessage("请再次按指纹...");
				mProgressDialog.show();
			case UIHelper.FINGERPRINT_ONMATCH_SUCCESS:// image--图片合成成功

				break;

			default:
				break;
			}
		};

	};

	// 指纹验证结果回调
	private Handler mMatchHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			if (mProgressDialog != null) {
				mProgressDialog.dismiss();
			}
			switch (msg.what) {
			case 100:
				// 匹配成功
				int pageId = msg.arg1;
				getUserInfoById(pageId);
				break;
			case 101:
				// 匹配失败
				Toast.makeText(mContext, "没有找到匹配的指纹", Toast.LENGTH_SHORT)
						.show();
				break;

			default:
				break;
			}
		};
	};
	private FingerPrintBean mFingerPrintBean;

	// 根据指纹获取当前用户的id
	private void getUserInfoById(int pageId) {
		//
		try {
			mFingerPrintBean = mKjdb.findById(pageId, FingerPrintBean.class);
			// 选择矫正人员
			if (mFingerPrintBean != null && mFingerPrintBean.getType() == 2) {
				chooseRecordInfo();
			}else {
				Toast.makeText(mContext, "匹配失败", Toast.LENGTH_SHORT).show();
			}
		} catch (Exception e) {
			Toast.makeText(mContext, "匹配失败", Toast.LENGTH_SHORT).show();
		}
	}

	// 选取矫正人员
	private void chooseRecordInfo() {
		Intent intent = new Intent(WorkVisitActivity.this, RecordActivity.class);
		intent.putExtra(RecordActivity.RECORD_STATE,
				RecordActivity.CHOOSE_RECORD_STATE);
		startActivityForResult(intent, CHOOSE_RECORD_REQUEST_OK);
	}

	private void takePhoto() {
		// 拍照
		new AlertDialog.Builder(this)
				.setTitle("拍照")
				.setMessage("是否进行拍照？")
				.setCancelable(true)
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						Intent takePicture = new Intent(WorkVisitActivity.this,
								ChoosePhotoActivity.class);
						takePicture.putExtra(
								ChoosePhotoActivity.CHOOSE_PHOTO_COUNT,
								mChooseImageCount);
						startActivityForResult(takePicture,
								DialogHelper.CHOOSE_PHOTO_REQUEST_OK);
					}

				})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// 提示录音
						dialog.dismiss();
						recording();
					}

				}).create().show();
	}

	// 开启录音
	private void recording() {
		// 拍照
		new AlertDialog.Builder(this).setTitle("录音").setMessage("是否进行录音？")
				.setCancelable(true)
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						soundRecord();
					}

				})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// 提示录音
						dialog.dismiss();
					}

				}).create().show();
	}

	private void soundRecord() {
		final int state = mService.getRecordState();
		switch (state) {
		case SoundRecorder.STATE_RECORDING:
			Toast.makeText(this, "正在录音中...", Toast.LENGTH_SHORT).show();
			return;
		case SoundRecorder.STATE_IDLE:
			mRemainingTimeCalculator.reset();
			mService.stopAudioPlayback();
			mService.setNotificationClass(this.getClass());
			
			if ((mAudioManager.getMode() == AudioManager.MODE_IN_CALL)
					&& (mAudioSourceType == MediaRecorder.AudioSource.MIC)) {
				mAudioSourceType = MediaRecorder.AudioSource.VOICE_UPLINK;
				mService.setAudioSourceType(mAudioSourceType);
				Log.e(TAG, "Selected Voice Tx only Source: sourcetype"
						+ mAudioSourceType);
			}
			
			mService.record(mRequestedType);
			return;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.kymjs.aframe.ui.activity.KJFrameActivity#registerBroadcast()
	 */
	@Override
	public void registerBroadcast() {
		// TODO Auto-generated method stub
		super.registerBroadcast();
		initLocationBroadcast();
	}

	// 初始化获取当前位置的广播
	private void initLocationBroadcast() {
		mLocationClient = ((AppContext) getApplication()).mLocationClient;
		mLocationClient.start();
		mLocationBroadcastReceiver = new LocationBroadcastReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(MyLocationListener.LOCATION_INTENT);
		registerReceiver(mLocationBroadcastReceiver, filter);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.kymjs.aframe.ui.activity.KJFrameActivity#unRegisterBroadcast()
	 */
	@Override
	public void unRegisterBroadcast() {
		// TODO Auto-generated method stub
		super.unRegisterBroadcast();
		if (mLocationBroadcastReceiver != null) {
			unregisterReceiver(mLocationBroadcastReceiver);
		}
		if (mLocationClient != null) {
			mLocationClient.stop();
		}
	}

	// 获取当前的位置
	private class LocationBroadcastReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {

			if (intent != null
					&& intent.getAction().equals(
							MyLocationListener.LOCATION_INTENT)) {

				mLocationBean = (LocationBean) intent
						.getSerializableExtra(MyLocationListener.LOCATION_KEY);
				Log.i(TAG, "-----> LocationBroadcastReceiver " + mLocationBean);
			}

		}
	};

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.kymjs.aframe.ui.activity.KJFrameActivity#widgetClick(android.view
	 * .View)
	 */
	@Override
	public void widgetClick(View v) {
		super.widgetClick(v);
		switch (v.getId()) {
		case R.id.header_back:
			KJActivityManager.create().finishActivity(this);
			break;
		case R.id.work_visit_button_sign_in:
			// 签到拍照
			SignIn();
			break;
		case R.id.work_visit_button_upload:
			// 记录上传
			mProgressDialog.setMessage("请稍等，正在上传记录...");
			mProgressDialog.show();
			InsertVisitSyncLogic logic = new InsertVisitSyncLogic(mAppContext,
					mInsertVisitHandler, true);
			logic.execute();
			break;

		default:
			break;
		}
	}

	// 签到拍照
	private void SignIn() {
		// 1.工作人员指纹签到
		showPopWindow();
		// 2.选择矫正人员
		// 3.提示拍照
		// 4.提示录音
	}

	private Handler mInsertVisitHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			if (mProgressDialog != null) {
				mProgressDialog.dismiss();
			}
			switch (msg.what) {
			case UIHelper.WORK_VISIT_UPLOAD_SUCCESS:
				// 上传图片
				UploadToTempSyncLogic logic = new UploadToTempSyncLogic(
						mAppContext, mInsertVisitHandler, true, 4);
				logic.execute();
				break;
			case UIHelper.WORK_VISIT_UPLOAD_FAIL:
				Toast.makeText(mContext, "记录上传失败", Toast.LENGTH_SHORT).show();
				break;
			case UIHelper.FILE_UPLOAD_SUCCESS:
				Toast.makeText(mContext, "记录上传成功", Toast.LENGTH_SHORT).show();
				break;
			case UIHelper.FILE_UPLOAD_FAIL:
				Toast.makeText(mContext, "记录上传失败", Toast.LENGTH_SHORT).show();
				break;

			default:
				break;
			}
		};
	};

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		WorkVisitBean bean = (WorkVisitBean) parent.getItemAtPosition(position);
		if (bean != null) {
			Intent intent = new Intent(WorkVisitActivity.this,
					WorkVisitDetailActivity.class);
			intent.putExtra("WorkVisitBean", bean);
			startActivity(intent);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		Log.i(TAG, "---> onActivityResult requestCode:" + requestCode + "resultCode:" + resultCode);
		if (requestCode == CHOOSE_PHOTO_REQUEST_OK && resultCode == 1001) {
			// beginDailyReport();
			if (data != null) {
				mCacheCheckImages = data
						.getStringArrayListExtra("mCacheCheckImages");
				// 保存图片到数据库
				if (mCacheCheckImages != null && !mCacheCheckImages.isEmpty()) {
					Message message = new Message();
					message.what = 100;
					mSavePhotoHandler.sendMessage(message);
				}
			}
		}
		if (requestCode == CHOOSE_RECORD_REQUEST_OK && resultCode == RESULT_OK) {
			if (data != null) {
				mRecordBean = (RecordBean) data
						.getSerializableExtra("RecordBean");
				if (mRecordBean != null
						&& !StringUtils.isEmpty(mRecordBean.getElectronicsId())) {
					// 1.保存信息
					saveWorkVisitInfo();
				} else {
					Toast.makeText(mContext, "选择失败，请重新选择矫正人员信息",
							Toast.LENGTH_SHORT).show();
				}
			}
		}
	}

	private void saveWorkVisitInfo() {
		if (mRecordBean != null && mFingerPrintBean != null
				&& mLocationBean != null) {
			WorkVisitBean bean = new WorkVisitBean();
			bean.setUserId(mFingerPrintBean.getUserId());
			bean.setUserName(mFingerPrintBean.getUserName());
			bean.setRymcId(mRecordBean.getElectronicsId());
			bean.setRymcName(mRecordBean.getName());
			bean.setMachId(mRecordBean.getRegisteredId());
			bean.setMachName(mRecordBean.getRegistered());
			bean.setInterViewTime(System.currentTimeMillis());
			bean.setInterViewWqk("遵守规定");
			bean.setInterViewAddress(mLocationBean.getAddress());
			bean.setLatitude(mLocationBean.getLatitude());
			bean.setLongitude(mLocationBean.getLontitude());
			bean.setState(1);
			mKjdb.saveBackId(bean);			// 获取当前保存的id
			DbModel dbModel = mKjdb
					.findDbModelBySQL("select max(id) as id from table_workVisit order by id desc");
			mMaxId = dbModel.getInt("id");
			bean.setId(mMaxId);
			mWorkVisitAdapter.addOne(bean);
			Log.i(TAG, "----> saveWorkVisitInfo mMaxId:" + mMaxId);
			// 提示拍照
			takePhoto();
		}else {
			Toast.makeText(mContext, "选择失败", Toast.LENGTH_SHORT).show();
		}
	}

	private Handler mSavePhotoHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 100:
				savePhoto();
				//TODO 开启录音
				recording();
				break;

			default:
				break;
			}
		};
	};

	// 把选取的图片保存到数据库
	private void savePhoto() {
		if (mCacheCheckImages != null && !mCacheCheckImages.isEmpty()) {
			int size = mCacheCheckImages.size();
			for (int i = 0; i < size; i++) {
				String photoPath = mCacheCheckImages.get(i);
				Log.i(TAG, "---> savePhoto:" + photoPath);
				ImageOrAudioBean bean = DataHelper
						.getImageOrAudioBeanInfoByPath(this, photoPath, 1);
				bean.setServiceId(4);
				bean.setParentId(String.valueOf(mMaxId));
				Log.i(TAG, "---> savePhoto " + bean);
				mKjdb.save(bean);
			}
		} else {
			Toast.makeText(this, "选取图片失败", Toast.LENGTH_SHORT).show();
		}
	}
	
	@Override
	protected void onStop() {
		super.onStop();
		if (mLogic != null) {
			mLogic.destory();
		}
		MtRfid.getInstance().RfidClose(); // Close
		//FingerprintManager.getInstance().closeSerialPort();
	}

	private void showSaveRecordDialog() {
		LayoutInflater inflater = LayoutInflater.from(this);
		View contentView = inflater.inflate(R.layout.recordsave_dialog, null);
		AlertDialog.Builder build = new AlertDialog.Builder(this);
		final EditText renameView = (EditText) contentView
				.findViewById(R.id.record_renme_et);
		if (mLastFileName == null) {
			String path = mService.getRecordSampleFile().getName();
			String fileName = path.substring(
					1 + path.lastIndexOf(File.separator), path.length());
			if (fileName.endsWith(".tmp"))
				fileName = fileName.substring(0, fileName.lastIndexOf(".tmp"));
			mLastFileName = fileName;
		}
		renameView.setText(mLastFileName);
		renameView.setSelection(mLastFileName.length());
		build.setView(contentView);
		build.setTitle(R.string.record_rename);
		build.setCancelable(false);
		build.setPositiveButton(R.string.save_record,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						try {
							Field f = dialog.getClass().getSuperclass()
									.getDeclaredField("mShowing");
							f.setAccessible(true);
							f.set(dialog, false);
						} catch (Exception e) {
							e.printStackTrace();
						}

						String newName = renameView.getText().toString();
						if (newName != null && !newName.equals(mLastFileName)) {
							mLastFileName = newName;
						}

						if (saveSample()) {
							try {
								Field f = dialog.getClass().getSuperclass()
										.getDeclaredField("mShowing");
								f.setAccessible(true);
								f.set(dialog, true);
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}
				});
		build.setNegativeButton(android.R.string.cancel,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						try {
							Field f = dialog.getClass().getSuperclass()
									.getDeclaredField("mShowing");
							f.setAccessible(true);
							f.set(dialog, true);
						} catch (Exception e) {
							e.printStackTrace();
						}
						mService.deleteRecord();
						mLastFileName = null;
					}
				});

		AlertDialog renameDialog = build.create();
		renameDialog.show();
		final Button positiveButton = renameDialog
				.getButton(AlertDialog.BUTTON_POSITIVE);
		renameView.addTextChangedListener(new TextWatcher() {
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if (s.toString().length() <= 0
						|| s.toString().matches(".*[/\\\\:*?\"<>|].*")
						|| !s.toString().matches(
								"[a-zA-Z0-9_.\\-\\s\u4e00-\u9fa5]+")) {
					String inputText = "";
					try {
						inputText = s.subSequence(start, start + count)
								.toString();
					} catch (IndexOutOfBoundsException ex) {
					}
					if (inputText.length() > 0
							&& ((inputText.matches(".*[/\\\\:*?\"<>|].*")) || !s
									.toString()
									.matches(
											"[a-zA-Z0-9_.\\-\\s\u4e00-\u9fa5]+"))) {
						Toast.makeText(WorkVisitActivity.this,
								R.string.invalid_char_prompt,
								Toast.LENGTH_SHORT).show();
					}
					if (positiveButton != null) {
						positiveButton.setEnabled(false);
					}
				} else {
					if (positiveButton != null) {
						positiveButton.setEnabled(true);
					}
				}
			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
			}
		});
	}

	private boolean saveSample() {
		if (mService.saveRecord(mLastFileName, mRequestedType)) {
			// 保存音频资源到数据库
			ImageOrAudioBean bean = new ImageOrAudioBean();
			bean.setFileName(mLastFileName);
			bean.setFileType(2);
			bean.setParentId(String.valueOf(mMaxId));
			String path = mRecorder.getSampleDir().getAbsolutePath() + "/"
					+ mLastFileName + mRecorder.getType();
			bean.setFilePath(path);
			bean.setState(1);
			bean.setImie(mAppContext.getImei());
			mKjdb.save(bean);
			return true;
		} else {
			mLastFileName = null;
			return false;
		}
	}

	@Override
	public void onStateChanged(int state) {
		if (state == SoundRecorder.STATE_STOP_RECORDING) {
			showSaveRecordDialog();
		}
	}

	@Override
	public void onError(int error) {
		// TODO Auto-generated method stub
		
	}
}
